package cn.iocoder.yudao.module.system.service.a_pictures;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
import cn.iocoder.yudao.module.system.config.a_gaojian.ConnectionConfig;
import cn.iocoder.yudao.module.system.config.a_gaojian.DlIvrsConfig;
import cn.iocoder.yudao.module.system.controller.admin.a_pictures.vo.*;
import cn.iocoder.yudao.module.system.dal.dataobject.a_pictures.PicturesDO;
import cn.iocoder.yudao.module.system.dal.dataobject.a_pictures.PicturesDOReq;
import cn.iocoder.yudao.module.system.dal.mysql.a_pictures.PicturesMapper;
import cn.iocoder.yudao.module.system.service.a_picturesLog.PicturesLogService;
import cn.iocoder.yudao.module.system.service.hybase.HyBaseService;
import cn.iocoder.yudao.module.system.service.ivrs.IvrsService;
import cn.iocoder.yudao.module.system.util.a_gaojian.*;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.trs.hybase.client.*;
import com.trs.hybase.client.params.OperationParams;
import com.trs.hybase.client.params.SearchParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @author lxj
 */
@Service
@Validated
@Slf4j
public class PicturesServiceImpl implements PicturesService {

    @Resource
    PicturesLogService picturesLogService;

    @Resource
    PicturesMapper picturesMapper;

    @Resource
    private DlIvrsConfig dlIvrsConfig;

    @Resource
    private IvrsService ivrsService;

    @Resource
    private HyBaseService hyBaseService;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    ImageUploadServiceImpl imageUploadService;

    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${fileData.picturePath}")
    private String path;

    /**
     * 删除文件存储在本地的根路径
     */
    @Value("${fileData.delPath}")
    private String delPath;
    /**
     * 图片表名
     */
    @Value("${hybase.dbname.pictures}")
    private String dbName;

    @Value("${ai.url}")
    private String dl_base_urs;

    @Value("${ip}")
    private String ip;

    @Value("${file.storage}")
    private String FILE_STORAGE;

    @Value("${file.image.host}")
    private String imageHost;

    @Value("${file.image.path}")
    private String imagePath;

    /**
     * 资源库接口地址
     */
    @Value("${reslib.url}")
    private String reslibUrl;

    /**
     * 资源库token
     */
    @Value("${reslib.token}")
    private String reslibToken;

    @Override
    public String upload(MultipartFile imageFile) {

        String address;
        try {
            BufferedImage bufferedImage = ImageIO.read(imageFile.getInputStream()); // 通过MultipartFile得到InputStream，从而得到BufferedImage
            System.out.println(bufferedImage.getWidth());
            System.out.println(bufferedImage.getHeight());
            address = ImageUtils.upload(path, imageFile);

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
        //总路径
        String url = address;
        String name = imageFile.getOriginalFilename();
        String extension = ImageUtils.getExtension(imageFile);
        //扩展名
        System.out.println("extension = " + extension);
        //名称
        System.out.println("name = " + name);
        //上传文件存储在本地的根路径
        System.out.println("path = " + path);
        System.out.println("url = " + url);
        //extension = png   扩展名
        //String name = createReqVO.getImageFile().getOriginalFilename();   名称
        //name = d60b90dd21bee4052c26730ebc39ee4.png
        //path = D:/idea/jfj    上传文件存储在本地的根路径
        //url = /2023-11-28/e823bec74b4b4f0b8137dcf64ab372ab.png
        //这里可以将需要的字段保存至数据库

        return url;
    }

    public void create(PicturesReqVO createReqVO) {
        createReqVO = upload(createReqVO);
        //添加图片表
        insertHybaseByImg(createReqVO);
    }

    @Override
    @Transactional
    public String insertHybaseByImg(PicturesReqVO createReqVO) {
        createReqVO = upload(createReqVO);
        File dest = new File(createReqVO.getUrl());
        System.out.println("新增图片文件上传地址：" + createReqVO.getUrl());

        String feature = imageFeatures(dest);

        createReqVO.setCreateTime(DateUtils.formatDateToStr(new Date()));
        createReqVO.setLastModificationTime(createReqVO.getCreateTime());
        //创建与服务器的连接实例
        TRSConnection conn = ConnectionConfig.getTRSConnection();
        //创建记录对象
        List<TRSInputRecord> recordList = new ArrayList<>();
        TRSInputRecord record = new TRSInputRecord();
        String uuid = IdUtil.fastSimpleUUID();
        TRSReport trsReport = new TRSReport();
        //添加字段
        try {
            record.addColumn("id", uuid);
            record.addColumn("author", createReqVO.getAuthor());
            record.addColumn("pic_create_time", createReqVO.getCreateTime());
            record.addColumn("keyword", createReqVO.getKeyword());
            record.addColumn("suffix", createReqVO.getSuffix());
            record.addColumn("pic_resolution", createReqVO.getPicResolution());
            record.addColumn("source", createReqVO.getSource());
            record.addColumn("category", createReqVO.getCategory());
            record.addColumn("url", createReqVO.getUrl());
            record.addColumn("content", createReqVO.getContent());
            record.addColumn("version", 1);
            record.addColumn("watermark", createReqVO.getWatermark());
            record.addColumn("height", createReqVO.getHeight());
            record.addColumn("width", createReqVO.getWidth());
            record.addColumn("fileName", createReqVO.getFileName());
            record.addColumn("create_time", createReqVO.getCreateTime());
            record.addColumn("last_modification_time", createReqVO.getLastModificationTime());
            record.addColumn("deleted", 0);
            record.addColumn("review_status", 0);
            record.addColumn("create_user_id", WebFrameworkUtils.getLoginUserId());
            record.addColumn("feature", feature);
            recordList.add(record);
            record.getUid();
            //执行插入记录（暂时在内存中）
            conn.executeInsert(dbName, recordList, new OperationParams(), trsReport);
            if (trsReport.getInsertedNum() > 0) {
                //新增到kingbase
                PicturesDO picturesDO = new PicturesDO();
                picturesDO.setFeature(feature);
                BeanUtils.copyProperties(createReqVO,picturesDO);
                picturesMapper.insert(picturesDO);
                return uuid;
            }
        } catch (TRSException e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public String save(PicturesBaseVO picturesDO) {
            // 图像特征提取
//            if (picturesDO.getFeature() == null || picturesDO.getFeature().equals("")){
//                picturesDO = feature(picturesDO);
//            }
            // 复制属性并保存到kingbase数据库
            PicturesDO finalPicturesDO = new PicturesDO();
            BeanUtils.copyProperties(picturesDO, finalPicturesDO);
            boolean isSaved = picturesMapper.save(finalPicturesDO);
            log.info("图片保存:{}", isSaved);

            return finalPicturesDO.getId().toString();
    }

    public PicturesBaseVO feature(PicturesBaseVO picturesDO){
        File dest = new File(imagePath + "/" + picturesDO.getRelativePath());
        log.info("新增图片文件上传路径：{}", imagePath + "/" + picturesDO.getRelativePath());
        picturesDO.setFeature(imageFeatures(dest));
        return picturesDO;
    }

    private Map<String,Object> ConvertKeys(Map<String,Object> map) {
        Map<String,Object> convertMap = new HashMap<>();
        // 遍历原始 Map 的键
        for (String key : map.keySet()) {
            StringBuilder convertedKey = new StringBuilder();
            for (char c : key.toCharArray()) {
                // 检查字符是否为大写字母
                if (Character.isUpperCase(c) && convertedKey.length() > 0) {
                    convertedKey.append('_');
                }
                // 将字符添加到结果中
                convertedKey.append(c);
            }
            // 将转换后的键和原值放入新 Map
            convertMap.put(convertedKey.toString().toLowerCase(), map.get(key));
        }
        System.out.println("Converted Map: " + convertMap);
        return convertMap;
    }

    private PicturesDOReq upload(PicturesDOReq picturesDO) {
        String address;
        try {
            // 通过MultipartFile得到InputStream，从而得到BufferedImage
            BufferedImage bufferedImage = ImageIO.read(picturesDO.getImageFile().getInputStream());
            picturesDO.setHeight(bufferedImage.getHeight());
            picturesDO.setWidth(bufferedImage.getWidth());
            picturesDO.setPicResolution(bufferedImage.getWidth() + "×" + bufferedImage.getHeight());
            address = ImageUtils.upload(path, picturesDO.getImageFile());
        } catch (IOException e) {
            e.printStackTrace();
            log.info("ERROR 读取图片失败，请检查图片或路径是否正确！");
            throw new RuntimeException();
        }
        //总路径
        String url = address;
        String extension = ImageUtils.getExtension(picturesDO.getImageFile());
        //这里可以将需要的字段保存至数据库
        picturesDO.setSuffix(extension);
        picturesDO.setUrl(path + url);

        return picturesDO;
    }

    /**
     * 图像特征提取
     *
     * @param file
     * @return
     */
    public String imageFeatures(File file) {
        String uri = "/irs_feature/image/file";
        System.out.println("dl_base_urs:" + dl_base_urs);
        HttpRequest request = HttpRequest.post(dl_base_urs + uri);
        request.form("file", file);
        cn.hutool.http.HttpResponse response = request.execute();
        if (response.isOk()) {
            String result = response.body();
            JSONObject jsonObject = JSON.parseObject(result);
            int code = jsonObject.getInteger("code");
            if (code == 1) {
                return jsonObject.getJSONObject("result").getString("image_org_feature");
            } else {
                return "";
            }
        } else {
            log.error("image get features fail:" + response.body());
            return "";
        }
    }


    private PicturesReqVO upload(PicturesReqVO picturesReqVO) {
        String address;
        try {
            // 通过MultipartFile得到InputStream，从而得到BufferedImage
            BufferedImage bufferedImage = ImageIO.read(picturesReqVO.getImageFile().getInputStream());
            picturesReqVO.setHeight(bufferedImage.getHeight());
            picturesReqVO.setWidth(bufferedImage.getWidth());
            picturesReqVO.setPicResolution(bufferedImage.getWidth() + "×" + bufferedImage.getHeight());
            address = ImageUtils.upload(path, picturesReqVO.getImageFile());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
        //总路径
        String url = address;
        String extension = ImageUtils.getExtension(picturesReqVO.getImageFile());
        //这里可以将需要的字段保存至数据库
        picturesReqVO.setSuffix(extension);
        picturesReqVO.setFileName(picturesReqVO.getImageFile().getOriginalFilename());
        picturesReqVO.setUrl(path + url);

        return picturesReqVO;
    }

    @Override
    public PageResult<PicturesPageReqVO> getPage(PicturesPageReqVO pageReqVO) {
        PageResult<PicturesPageReqVO> pageResult = new PageResult<>();
        List<PicturesPageReqVO> picturesReqVOList = new ArrayList<>();
        //创建与服务器的连接实例
        TRSConnection conn = ConnectionConfig.getTRSConnection();
        SearchParams param = new SearchParams();
        //设置结果排序方式为创建时间排序
        param.setSortMethod("-create_time");
        //设置返回结果字段
//        param.setReadColumns("id;content;author;pic_create_time;keyword;suffix;create_user_id;pic_resolution;source;review_status;category;url;version;watermark;height;width;create_time;last_modification_time;fileName");
        TRSResultSet resultSet;
        Long userId = WebFrameworkUtils.getLoginUserId();
        String whereStr = (StringUtils.isNotBlank(pageReqVO.getIsShare())) ? "deleted:0 AND is_share:1" : "deleted:0 AND create_user_id:" + userId;
        //高 height 宽 width 类别 category 关键词 keyword 描述 content
        if (pageReqVO.getHeight() != null) {
            whereStr += " AND height:" + pageReqVO.getHeight();
        }
        if (pageReqVO.getWidth() != null) {
            whereStr += " AND width:" + pageReqVO.getWidth();
        }
        if (StringUtils.isNotBlank(pageReqVO.getCategory())) {
            whereStr += " AND category:" + pageReqVO.getCategory();
        }
        if (StringUtils.isNotBlank(pageReqVO.getKeyword())) {
            whereStr += " AND keyword:" + pageReqVO.getKeyword();
        }
        if (StringUtils.isNotBlank(pageReqVO.getContent())) {
            whereStr += " AND content:" + pageReqVO.getContent();
        }

        try {
            //在"pictures"数据库里检索
            //resultSet = conn.executeSelect("pictures", whereStr, ((pageReqVO.getPageNo() - 1) * pageReqVO.getPageSize()), pageReqVO.getPageSize(), param);
            resultSet = conn.executeSelect(dbName, whereStr, (pageReqVO.getPageNum() - 1), pageReqVO.getPageSize(), param);
            if (resultSet != null) {
                for (int i = 0; i < resultSet.size(); i++) {
                    resultSet.moveNext();
                    TRSRecord re = resultSet.get();
                    PicturesPageReqVO picturesReqVO = new PicturesPageReqVO();
                    picturesReqVO.setId(re.getString("id"));
                    picturesReqVO.setContent(re.getString("content"));
                    picturesReqVO.setAuthor(re.getString("author"));
                    picturesReqVO.setPicCreateTime(re.getString("pic_create_time"));
                    picturesReqVO.setKeyword(re.getString("keyword"));
                    picturesReqVO.setSuffix(re.getString("suffix"));
                    picturesReqVO.setPicResolution(re.getString("pic_resolution"));
                    picturesReqVO.setSource(re.getString("source"));
                    picturesReqVO.setCategory(re.getString("category"));
                    picturesReqVO.setUrl(re.getString("url"));
                    picturesReqVO.setVersion(re.getInt("version"));
                    picturesReqVO.setWatermark(re.getInt("watermark"));
                    picturesReqVO.setHeight(re.getInt("height"));
                    picturesReqVO.setWidth(re.getInt("width"));
                    picturesReqVO.setCreateTime(re.getString("create_time"));
                    picturesReqVO.setLastModificationTime(re.getString("last_modification_time"));
                    picturesReqVO.setFileName(re.getString("fileName"));
                    picturesReqVO.setCreateUserId(re.getString("create_user_id"));
                    picturesReqVO.setReviewStatus(re.getInt("review_status"));
                    picturesReqVO.setIsShare(re.getString("is_share"));
                    picturesReqVO.setIsPush(re.getString("is_push"));
                    picturesReqVOList.add(picturesReqVO);
                }

                pageResult.setTotal(resultSet.getNumFound());
                pageResult.setList(picturesReqVOList);

            }
        } catch (TRSException e) {
            System.out.println("ErrorCode:" + e.getErrorCode());
            System.out.println("ErrorString:" + e.getErrorString());
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        return pageResult;
    }

    @Override
    public PageResult<PicturesDO> selectPage(PicturesPageReqVO dto) {
        return picturesMapper.page(dto);
    }

    @Override
    public PageResult<PicturesPageQukanReqVO> getPageQukan(PicturesPageQukanReqVO pageReqVO, Long userId) {
        PageResult<PicturesPageQukanReqVO> pageResult = new PageResult<>();
        List<PicturesDO> picturesDOS = picturesMapper.selectList("creator", userId);

        List<PicturesPageQukanReqVO> pageQukanReqVOList = picturesDOS.stream()
                .map(picturesDO -> {
                    PicturesPageQukanReqVO pageQukanReqVO = new PicturesPageQukanReqVO();
                    BeanUtils.copyProperties(picturesDO, pageQukanReqVO);
                    pageQukanReqVO.setId(picturesDO.getId().toString());
                    pageQukanReqVO.setUrl(picturesDO.getUrl());
                    return pageQukanReqVO;
                })
                .collect(Collectors.toList());

        pageResult.setTotal((long) picturesDOS.size());
        pageResult.setList(pageQukanReqVOList);

        return pageResult;
    }

    @Override
    public Boolean delete(String ids, String urls) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<String> urlList = Arrays.asList(urls.split(","));

        //创建与服务器的连接实例
        TRSConnection conn = ConnectionConfig.getTRSConnection();
        List<TRSInputRecord> newValues = new ArrayList<>();
        OperationParams params = new OperationParams();
        TRSReport trsReport = new TRSReport();
        params.setProperty("unique.column.search", "true");
        params.setProperty("unique.column", "id");
        try {
            for (int i = 0; i < idList.size(); i++) {
                TRSInputRecord record = new TRSInputRecord();
                record.addColumn("id", idList.get(i));
                record.addColumn("deleted", 1);
                record.addColumn("url", FileUtils.moveFile(delPath, urlList.get(i)));
                newValues.add(record);
            }
            conn.executeUpdate(dbName, newValues, params, trsReport);
        } catch (TRSException e) {
            e.printStackTrace();
        }
        return trsReport.getUpdatedNum() > 0;
       /* //创建与服务器的连接实例
        TRSConnection conn = ConnectionUtils.getTRSConnection();
        String[] strUrls = urls.split(",");
        List<String> delUrls = Arrays.asList(strUrls);
        try {
            conn.executeDelete(dbName, ids.split(","));
            //删除文件
            ImageUtils.deleteFileByFileNameAndPath(del_urls);
        } catch (TRSException e) {
            e.printStackTrace();
        }*/
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(Long[] ids) {
        for (Long id : ids) {
            picturesMapper.deleteById(id);
            //同步删除海贝
            CompletableFuture future = CompletableFuture.runAsync(() -> {
                hyBaseService.executeDeleteQuery(dbName, id);
            });
        }
        return true;
    }

    @Override
    public PicturesReqVO get(String id) {
        PicturesReqVO picturesReqVO = new PicturesReqVO();
        PicturesDO picturesDO = picturesMapper.selectOne("id", id);
        BeanUtils.copyProperties(picturesDO, picturesReqVO);
        return picturesReqVO;
    }

    @Override
    public PicturesDO getInfo(String id) {
        return picturesMapper.selectOne("id", id);
    }

    @Override
    public Boolean update(PicturesReqVO updateReqVO) {
        updateReqVO = upload(updateReqVO);
        return updateHybaseByImg(updateReqVO);
    }

    public Boolean updateHybaseByImg(PicturesReqVO updateReqVO) {
        updateReqVO.setVersion(updateReqVO.getVersion() + 1);
        updateReqVO.setLastModificationTime(DateUtils.formatDateToStr(new Date()));
        File file = new File(updateReqVO.getUrl());
        System.out.println("文件上传地址：" + updateReqVO.getUrl());
        String feature = imageFeatures(file);
        //创建与服务器的连接实例
        TRSConnection conn = ConnectionConfig.getTRSConnection();
        List<TRSInputRecord> newValues = new ArrayList<>();
        OperationParams params = new OperationParams();
        TRSReport trsReport = new TRSReport();
        params.setProperty("unique.column.search", "true");
        params.setProperty("unique.column", "id");
        try {
            TRSInputRecord record = new TRSInputRecord();
            record.addColumn("id", updateReqVO.getId());
            record.addColumn("suffix", updateReqVO.getSuffix());
            record.addColumn("pic_resolution", updateReqVO.getPicResolution());
            record.addColumn("url", updateReqVO.getUrl());
            record.addColumn("version", updateReqVO.getVersion());
            record.addColumn("height", updateReqVO.getHeight());
            record.addColumn("width", updateReqVO.getWidth());
            record.addColumn("last_modification_time", updateReqVO.getLastModificationTime());
            record.addColumn("fileName", updateReqVO.getFileName());
            record.addColumn("content", updateReqVO.getContent());
            record.addColumn("author", updateReqVO.getAuthor());
            record.addColumn("pic_create_time", updateReqVO.getPicCreateTime());
            record.addColumn("keyword", updateReqVO.getKeyword());
            record.addColumn("source", updateReqVO.getSource());
            record.addColumn("category", updateReqVO.getCategory());
            record.addColumn("watermark", updateReqVO.getWatermark());
            record.addColumn("feature", feature);
            newValues.add(record);

            PicturesReqVO picturesLog = get(updateReqVO.getId());
            if (!picturesLogService.findExistByRelevanceId(conn, updateReqVO.getId())) {
                picturesLogService.insertPicturesLog(conn, picturesLog);
            }

            conn.executeUpdate(dbName, newValues, params, trsReport);

            try {
                PicturesReqVO newPicturesReqVO = new PicturesReqVO();
                Map<String, Object> updateReqVOMap = ManuscriptLogUtils.objectToMap(updateReqVO);
                Map<String, Object> picturesLogMap = ManuscriptLogUtils.objectToMap(picturesLog);
                updateReqVOMap.remove("imageFile");
                picturesLogMap.remove("imageFile");
                Map<String, Object> newMap = ManuscriptLogUtils.mapCompare(updateReqVOMap, picturesLogMap);
                if (!newMap.isEmpty()) {
                    ObjectMapper objectMapper = new ObjectMapper();
                    newPicturesReqVO = objectMapper.convertValue(newMap, PicturesReqVO.class);
                }
                picturesLogService.insertPicturesLog(conn, newPicturesReqVO);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                log.error("图片修改日志添加失败", updateReqVO, e);
            }
        } catch (TRSException e) {
            e.printStackTrace();
        }
        return trsReport.getUpdatedNum() > 0;
    }

    @Override
    public long insertPicturesByDay() {
        //创建与服务器的连接实例
        TRSConnection conn = ConnectionConfig.getTRSConnection();
        SearchParams param = new SearchParams();
        TRSResultSet resultSet;
        String whereStr = "deleted:0 AND create_user_id:" + WebFrameworkUtils.getLoginUserId() + " AND create_time:[" + DateUtils.formatYYYYMMDDToStr(DateUtils.getDayStart(new Date())) + " TO " + DateUtils.formatYYYYMMDDToStr(DateUtils.getDayStart(new Date())) + "]";
        try {
            //在"pictures"数据库里检索
            resultSet = conn.executeSelect(dbName, whereStr, 0, 10000, param);
            if (resultSet != null) {
                return resultSet.getNumFound();
            }
        } catch (TRSException e) {
            System.out.println("ErrorCode:" + e.getErrorCode());
            System.out.println("ErrorString:" + e.getErrorString());
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        return 0;
    }

    @Override
    public Boolean updateReview(String id, Integer reviewStatus) {
        PicturesDO picturesDO = new PicturesDO();
        picturesDO.setId(Long.valueOf(id));
        picturesDO.setReviewStatus(reviewStatus);
        int i = picturesMapper.updateById(picturesDO);
        // 同步数据到海贝
        CompletableFuture.runAsync(() -> {
            Map<String,Object> map = new HashMap<>();
            map.put("id", id);
            map.put("review_status",reviewStatus);
            hyBaseService.updateHybaseById(dbName,Long.valueOf(id),map);
        });
        return i > 0;
    }

    @Override
    public String DlIvrs(String url, MultipartEntityBuilder builder) {

        String responseBody = null;
        // 创建HttpClient实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建HttpPost对象
            HttpPost httpPost = new HttpPost(url);
            // 设置请求体
            HttpEntity multipart = builder.build();
            httpPost.setEntity(multipart);
            // 执行请求
            HttpResponse response = httpClient.execute(httpPost);
            // 获取响应体
            HttpEntity responseEntity = response.getEntity();
            responseBody = EntityUtils.toString(responseEntity, "UTF-8");
            // 打印响应内容
            System.out.println(responseBody);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseBody;
    }

    @Override
    public PageResult<PicturesPageReqVO> getPageByFeature(PicturesPageReqVO pageReqVO, MultipartFile file) {

        PageResult<PicturesPageReqVO> pageResult = new PageResult<>();
        List<PicturesPageReqVO> picturesReqVOList = new ArrayList<>();
        //创建与服务器的连接实例
        TRSConnection conn = ConnectionConfig.getTRSConnection();
        SearchParams param = new SearchParams();
        //设置结果排序方式为创建时间排序
        param.setSortMethod("RELEVANCE;-feature");
        //设置返回结果字段
//        param.setReadColumns("id;content;author;pic_create_time;keyword;suffix;create_user_id;pic_resolution;source;review_status;category;url;version;watermark;height;width;create_time;last_modification_time;fileName");
        TRSResultSet resultSet;
        Long userId = WebFrameworkUtils.getLoginUserId();
        //高 height 宽 width 类别 category 关键词 keyword 描述 content

        try {
            String upload = ImageUtils.upload(path, file);
            String feature = imageFeatures(new File(path + upload));
            String whereStr = (StringUtils.isNotBlank(pageReqVO.getIsShare())) ? "deleted:0 AND is_share:1" : "deleted:0 AND create_user_id:" + userId + " AND feature: " + feature;
            //在"pictures"数据库里检索
            //resultSet = conn.executeSelect("pictures", whereStr, ((pageReqVO.getPageNo() - 1) * pageReqVO.getPageSize()), pageReqVO.getPageSize(), param);
            resultSet = conn.executeSelect(dbName, whereStr, (pageReqVO.getPageNum() - 1), pageReqVO.getPageSize(), param);
            if (resultSet != null) {
                for (int i = 0; i < resultSet.size(); i++) {
                    resultSet.moveNext();
                    TRSRecord re = resultSet.get();
                    PicturesPageReqVO picturesReqVO = new PicturesPageReqVO();
                    picturesReqVO.setId(re.getString("id"));
                    picturesReqVO.setContent(re.getString("content"));
                    picturesReqVO.setAuthor(re.getString("author"));
                    picturesReqVO.setPicCreateTime(re.getString("pic_create_time"));
                    picturesReqVO.setKeyword(re.getString("keyword"));
                    picturesReqVO.setSuffix(re.getString("suffix"));
                    picturesReqVO.setPicResolution(re.getString("pic_resolution"));
                    picturesReqVO.setSource(re.getString("source"));
                    picturesReqVO.setCategory(re.getString("category"));
                    picturesReqVO.setUrl(re.getString("url"));
                    picturesReqVO.setVersion(re.getInt("version"));
                    picturesReqVO.setWatermark(re.getInt("watermark"));
                    picturesReqVO.setHeight(re.getInt("height"));
                    picturesReqVO.setWidth(re.getInt("width"));
                    picturesReqVO.setCreateTime(re.getString("create_time"));
                    picturesReqVO.setLastModificationTime(re.getString("last_modification_time"));
                    picturesReqVO.setFileName(re.getString("fileName"));
                    picturesReqVO.setCreateUserId(re.getString("create_user_id"));
                    picturesReqVO.setReviewStatus(re.getInt("review_status"));
                    picturesReqVO.setIsShare(re.getString("is_share"));
                    picturesReqVO.setIsPush(re.getString("is_push"));
                    picturesReqVOList.add(picturesReqVO);
                }

                pageResult.setTotal(resultSet.getNumFound());
                pageResult.setList(picturesReqVOList);

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        return pageResult;
    }


    @Override
    public Boolean updateShare(String id, String shareStatus) {
        PicturesDO picturesDO = new PicturesDO();
        picturesDO.setId(Long.valueOf(id));
        picturesDO.setIsShare(shareStatus);
        int i = picturesMapper.updateById(picturesDO);
        // 同步数据到海贝
        CompletableFuture.runAsync(() -> {
            Map<String,Object> map = new HashMap<>();
            map.put("id", id);
            map.put("is_share",shareStatus);
            hyBaseService.updateHybaseById(dbName,Long.valueOf(id),map);
        });
        return i > 0;
    }

    @Override
    public Boolean updatePush(String id, String pushStatus) {
        PicturesDO picturesDO = getInfo(id);

        // 获取文件并上传
        MultipartFile multipartFile;
        try {
            multipartFile = FileToMultipartFileUtils.convertFileToMultipartFile(new File(imagePath + "/" +picturesDO.getRelativePath()));
        } catch (IOException e) {
            e.printStackTrace();
            log.info("文件 multipartFile 类型转换 File 类型失败，请检查文件是否正确！");
            return false;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.set("tenant-id", "1");
        headers.set("Authorization", "Bearer " + reslibToken);

        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", multipartFile.getResource());
        body.add("name", picturesDO.getFileName());
        body.add("author", picturesDO.getAuthor());
        body.add("source", "融媒生产系统");

        // 上传文件
        org.springframework.http.HttpEntity<MultiValueMap<String, Object>> entity = new org.springframework.http.HttpEntity<>(body, headers);
        ResponseEntity<CommonResult> response = restTemplate.postForEntity(reslibUrl + "picture/upload/10/sava", entity, CommonResult.class);
        if (response.getBody().getCode() != 200) return false;

        // 更新数据库
        picturesDO.setIsPush(pushStatus);
        int updateCount = picturesMapper.updateById(picturesDO);

        // 异步同步数据到海贝
        CompletableFuture.runAsync(() -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", id);
            map.put("is_push", pushStatus);
            hyBaseService.updateHybaseById(dbName, Long.valueOf(id), map);
        });

        return updateCount > 0;
    }


    @Override
    public Object downloadCount(String id) {
        int count = picturesMapper.downloadCount(id);
        return count;
    }

    /**
     * 根据图片id获取图片下载路径
     * @param id
     * @return
     */
    @Override
    public String getImageDownloadPath(String id) {
        PicturesDO picturesDO = picturesMapper.selectOne(new LambdaQueryWrapper<PicturesDO>().eq(PicturesDO::getId, id));
        if (picturesDO != null) {
            return picturesDO.getUrl();
        }else {
            return "";
        }
    }
}
